package com.tech47.email;

import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

 
public class EmailManager{
	private static final String MAIL_SMTP_HOST = "mail.smtp.host";
	private static String host;
	
    public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}
	public EmailManager() {
		setHost(EmailConfiguration.getString("EmailManager.0")); //$NON-NLS-1$
	}
	public static void sendMessage(String htmlMessage, String subjectLine, List<String> toList, String from) {
      Properties properties = System.getProperties();
      properties.setProperty(MAIL_SMTP_HOST, EmailConfiguration.getString("EmailManager.host"));
      Session session = Session.getDefaultInstance(properties);
      session.setDebug(true);
      //System.out.println("Sending mail.");
      try{
         Transport transport = session.getTransport(EmailConfiguration.getString("EmailManager.protocol"));
         transport.connect();
         MimeMessage mMessage = new MimeMessage(session);
         mMessage.setFrom(new InternetAddress(from));
         if (toList != null) {
        	 for (String to : toList) {
        		 mMessage.addRecipient(Message.RecipientType.TO,
                         new InternetAddress(to));
        	 }
         }
         mMessage.setSubject(subjectLine);
         MimeBodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText(htmlMessage,EmailConfiguration.getString("EmailManager.encode"),EmailConfiguration.getString("EmailManager.type")); //$NON-NLS-1$ //$NON-NLS-2$
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      mMessage.setContent(multipart);
      mMessage.saveChanges();
      transport.send(mMessage);
      //System.out.println("mail sent.");
      }catch (Exception mex) {
         mex.printStackTrace();
      }
   }
} 